<template>
  <div class="ongoing-contracts bg-gray-50 min-h-screen">
    <!-- 顶部导航栏 -->
    <header class="header">
      <div class="header-content d-flex justify-content-between align-items-center">
        <div class="d-flex align-items-center">
          <i class="fa fa-spinner fa-spin mr-3 text-primary" style="font-size: 28px;"></i>
          <h2>进行中的合同</h2>
        </div>
        <div class="d-flex align-items-center">
          <button @click="goBack" class="btn btn-secondary">
            <i class="fa fa-home mr-2"></i><span style="color: #212529;">返回主页</span>
          </button>
        </div>
      </div>
    </header>

    <main class="container mx-auto px-4 py-6">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container mt-4">
        <div class="spinner"></div>
        <p>加载合同数据中...</p>
      </div>

      <!-- 错误消息 -->
      <div v-if="errorMessage" class="error-container mt-4">
        <div class="error-message">
          <i class="fa fa-exclamation-circle mr-2"></i>{{ errorMessage }}
        </div>
      </div>

      <!-- 调试信息 - 移除标题 -->
      <div v-if="!loading && debugInfo" class="debug-info p-3 bg-light rounded-lg shadow-sm">
        <p class="text-sm text-gray-600">合同数量: {{ contracts.length }}</p>
      </div>

      <!-- 合同列表 -->
      <div v-if="!loading && contracts.length > 0" class="card mb-8 hover-effect">
        <div class="card-body p-5">
          <div class="contracts-table overflow-x-auto">
            <table class="table w-full min-w-[600px] border-collapse" style="table-layout: fixed;">
              <thead>
              <tr class="bg-gray-50">
                <th class="py-3 px-4 text-left text-sm font-medium text-gray-500 uppercase tracking-wider border-b-2 border-gray-200">合同ID</th>
                <th class="py-3 px-4 text-left text-sm font-medium text-gray-500 uppercase tracking-wider border-b-2 border-gray-200">合同名称</th>
                <th class="py-3 px-4 text-left text-sm font-medium text-gray-500 uppercase tracking-wider border-b-2 border-gray-200">创建时间</th>
                <th class="py-3 px-4 text-left text-sm font-medium text-gray-500 uppercase tracking-wider border-b-2 border-gray-200">操作</th>
              </tr>
              </thead>
              <tbody>
              <tr v-for="contract in contracts" :key="contract.id" class="border-b border-gray-200 hover:bg-gray-50 transition-colors duration-200">
                <td class="py-3 px-4 text-gray-700 border-b border-gray-200">{{ contract.id || '无ID' }}</td>
                <td class="py-3 px-4 text-gray-700 border-b border-gray-200">{{ contract.name || '无名称' }}</td>
                <td class="py-3 px-4 text-gray-700 border-b border-gray-200">{{ formatDate(contract.createTime) || '无时间' }}</td>
                <td class="py-3 px-4 border-b border-gray-200 flex items-center justify-center">
                  <button @click="viewContract(contract.id)" class="btn btn-info px-3 py-1.5 text-sm rounded-md flex items-center transition-all duration-200 shadow-sm">
                    <i class="fa fa-eye mr-1.5"></i>
                    <span>查看详情</span>
                  </button>
                </td>
              </tr>
              </tbody>
            </table>
          </div>

          <!-- 分页控件 -->
          <div class="pagination mt-6 flex flex-col md:flex-row justify-between items-start md:items-center">
            <div class="text-sm text-gray-600 mt-3 md:mt-0 text-right">
              每页显示 {{ pageSize }} 条，共 {{ totalItems }} 条
            </div>
            <div class="flex items-center">
              <button
                  @click="prevPage"
                  :disabled="currentPage === 0"
                  class="btn btn-sm btn-outline-secondary px-3 py-1.5 rounded-md flex items-center transition-all duration-200 mr-2 shadow-sm"
                  :class="{ 'opacity-50 cursor-not-allowed': currentPage === 0 }"
              >
                <i class="fa fa-chevron-left mr-1"></i>
                <span>上一页</span>
              </button>
              <span class="mx-2 text-sm text-gray-700 font-medium">
                第 {{ currentPage + 1 }} 页，共 {{ totalPages }} 页
              </span>
              <button
                  @click="nextPage"
                  :disabled="currentPage === totalPages - 1"
                  class="btn btn-sm btn-outline-secondary px-3 py-1.5 rounded-md flex items-center transition-all duration-200 ml-2 shadow-sm"
                  :class="{ 'opacity-50 cursor-not-allowed': currentPage === totalPages - 1 }"
              >
                <span>下一页</span>
                <i class="fa fa-chevron-right ml-1"></i>
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 无合同提示 -->
      <div v-else-if="!loading && contracts.length === 0" class="card mb-8 text-center py-8 hover-effect">
        <div class="card-body">
          <div class="empty-message">
            <div class="w-24 h-24 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4 shadow-sm">
              <i class="fa fa-file-contract text-3xl text-gray-400"></i>
            </div>
            <h4 class="text-xl font-semibold text-gray-800 mb-2">暂无进行中的合同</h4>
            <p class="text-gray-500 max-w-md mx-auto">没有正在履行中的合同记录</p>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<script>
import axios from 'axios'
import { ref, onMounted, watch } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'

export default {
  name: 'EmployeeOngoingContracts',
  setup() {
    const store = useStore()
    const router = useRouter()

    const loading = ref(true)
    const errorMessage = ref('')
    const contracts = ref([])
    const currentPage = ref(0)
    const pageSize = ref(10)
    const totalPages = ref(1)
    const totalItems = ref(0)
    const debugInfo = ref(true) // 启用调试信息

    // 用户信息
    const employeeId = ref(null)

    // 配置请求头
    const setupRequestHeaders = () => {
      if (store.state.user) {
        axios.defaults.headers.common['X-Employee-Id'] = store.state.user.id
        axios.defaults.headers.common['X-Employee-Position'] = store.state.user.position
      }
    }

    // 返回主页
    const goBack = () => {
      router.push('/employee/dashboard')
    }

    // 获取进行中的合同数据
    const fetchOngoingContracts = () => {
      loading.value = true
      errorMessage.value = ''

      if (!employeeId.value) {
        errorMessage.value = '用户信息加载中，请稍后...'
        loading.value = false
        return
      }

      axios.get(`/auth/contracts/ongoing/${employeeId.value}`, {
        headers: {
          'X-Employee-Id': employeeId.value,
          'X-Employee-Position': store.state.user?.position
        },
        params: {
          page: currentPage.value,
          size: pageSize.value
        }
      })
          .then(response => {
            if (response.data && Array.isArray(response.data.content)) {
              contracts.value = response.data.content
              totalItems.value = response.data.totalElements
              totalPages.value = response.data.totalPages
            } else {
              contracts.value = response.data || []
              totalItems.value = (response.data || []).length
              totalPages.value = Math.ceil(totalItems.value / pageSize.value)
            }
          })
          .catch(error => {
            console.error('获取进行中的合同失败', error)
            if (error.response) {
              errorMessage.value = error.response.data?.message || '获取合同失败，请稍后再试'
            } else {
              errorMessage.value = '网络错误，请检查连接'
            }
          })
          .finally(() => {
            loading.value = false
          })
    }

    // 查看合同详情
    const viewContract = (contractId) => {
      router.push(`/employee/contracts/${contractId}/progress`)
    }

    // 分页操作
    const prevPage = () => {
      if (currentPage.value > 0) {
        currentPage.value--
        fetchOngoingContracts()
      }
    }

    const nextPage = () => {
      if (currentPage.value < totalPages.value - 1) {
        currentPage.value++
        fetchOngoingContracts()
      }
    }

    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return ''
      try {
        const date = new Date(dateString)
        return date.toLocaleDateString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        })
      } catch (e) {
        return '日期格式错误'
      }
    }

    onMounted(() => {
      if (store.state.user) {
        employeeId.value = store.state.user.id
        setupRequestHeaders()
        fetchOngoingContracts()
      }
    })

    // 监听用户信息变化
    watch(() => store.state.user?.id, () => {
      if (store.state.user) {
        employeeId.value = store.state.user.id
        fetchOngoingContracts()
      }
    })

    return {
      loading,
      errorMessage,
      contracts,
      currentPage,
      pageSize,
      totalPages,
      totalItems,
      goBack,
      viewContract,
      prevPage,
      nextPage,
      formatDate,
      debugInfo
    }
  }
}
</script>

<style scoped>
/* 基础样式定义 */
:root {
  --primary-color: #3b82f6;
  --secondary-color: #6b7280;
  --warning-color: #f59e0b;
  --info-color: #06b6d4;
  --success-color: #10b981;
}

/* 公共样式 */
.header {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  padding: 15px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.header-content {
  width: 100%;
}

.btn {
  display: inline-flex;
  align-items: center;
  padding: 0.375rem 0.75rem;
  border-radius: 0.375rem;
  text-decoration: none;
  cursor: pointer;
  transition: all 0.3s;
  font-weight: 500;
  font-size: 0.875rem;
  border: none;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.btn-primary { background-color: var(--primary-color); color: white; }
.btn-secondary { background-color: var(--secondary-color); }
.btn-info { background-color: var(--info-color); color: #212529; }
.btn-warning { background-color: var(--warning-color); color: #212529; }
.btn-outline-secondary {
  background-color: white;
  color: var(--secondary-color);
  border: 1px solid var(--secondary-color);
}

.btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 15px rgba(0, 0, 0, 0.1);
}

.card {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  transition: transform 0.3s, box-shadow 0.3s;
}

.hover-effect {
  transition: transform 0.3s, box-shadow 0.3s;
}

.hover-effect:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.table {
  width: 100%;
  border-collapse: collapse;
}

.table th, .table td {
  padding: 0.75rem;
  vertical-align: middle;
  border-bottom: 1px solid #e5e7eb;
  word-break: break-word;
  font-size: 0.875rem;
}

.table th {
  font-weight: 500;
  color: #4b5563;
  text-transform: uppercase;
  letter-spacing: 0.05em;
  border-bottom: 2px solid #e5e7eb;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.table tbody tr {
  vertical-align: middle;
}

/* 加载状态样式 */
.loading-container {
  text-align: center;
  padding: 50px;
}

.spinner {
  width: 40px;
  height: 40px;
  margin: 0 auto;
  border: 4px solid #f3f3f3;
  border-top: 4px solid var(--primary-color);
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 错误提示样式 */
.error-container {
  text-align: center;
  padding: 50px;
}

.error-message {
  color: #e74c3c;
  font-size: 16px;
  padding: 10px;
  border-radius: 4px;
  background-color: #f8d7da;
  display: inline-block;
}

/* 空状态样式 */
.empty-message i {
  color: #adb5bd;
}
</style>